package com.kang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kang.entity.BookMark;
import com.kang.entity.Essay;
import com.kang.entity.SysUser;
import com.kang.mapper.BookMarkMapper;
import com.kang.mapper.EssayMapper;
import com.kang.mapper.UserMapper;
import com.kang.service.BookMarkService;
import com.kang.util.ThreadLocalUtil;
import com.kang.util.TokenToUserId;
import com.kang.vo.ParamInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BookMarkServiceImpl extends ServiceImpl<BookMarkMapper, BookMark> implements BookMarkService {

    @Autowired
    private BookMarkMapper bookMarkMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private EssayMapper essayMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Integer insertBookMark(HttpServletRequest request,Integer essayId) throws Exception {
        Integer userId = TokenToUserId.TokenGetUserId(request.getHeader("token"));
        BookMark bookMark = new BookMark();
        bookMark.setUserId(userId);
        bookMark.setEssayId(essayId);
        bookMark.setCreateTime(new Date());
        bookMark.setUpdateTime(new Date());
        //收藏量存在redis做定时更新数据操作
        int insert = bookMarkMapper.insert(bookMark);
        if (insert == 1) {
            stringRedisTemplate.opsForValue().increment("user:bookMark:" + essayId);
        }
        return insert;
    }

    @Override
    public Integer updateBookMark(HttpServletRequest request, Integer essayId) throws Exception {
        Integer userId = TokenToUserId.TokenGetUserId(request.getHeader("token"));
        QueryWrapper<BookMark> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId).eq("essay_id",essayId);
        int delete = bookMarkMapper.delete(wrapper);
        if (delete == 1) {
            stringRedisTemplate.opsForValue().decrement("user:bookMark:" + essayId);
        }
        return delete;
    }

    @Override
    public Page<Essay> getBookMarkList(ParamInfo paramInfo) {
        Integer userId = ThreadLocalUtil.getCurrentUser().getId();
        QueryWrapper<BookMark> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<BookMark> bookMarkIds = bookMarkMapper.selectList(wrapper);
        List<Integer> collect = bookMarkIds.stream().map(BookMark::getEssayId).collect(Collectors.toList());
        QueryWrapper<Essay> queryWrapper = new QueryWrapper<>();
        if (collect.size() != 0) {
            Page<Essay> page = new Page<>(paramInfo.getPageNum(), paramInfo.getPageSize());
            queryWrapper.in("id",collect);
            Page<Essay> essayPage = essayMapper.selectPage(page, queryWrapper);
            List<Integer> userIdList = essayPage.getRecords().stream().map(Essay::getUserId).collect(Collectors.toList());
            if (userIdList.size() != 0) {
                List<SysUser> userList = userMapper.selectList(new QueryWrapper<SysUser>().in("id", userIdList));
                essayPage.getRecords().forEach(v -> {
                    for (SysUser user : userList) {
                        if (v.getUserId().equals(user.getId())) {
                            v.setUsername(user.getUsername());
                            v.setHeadUrl(user.getHeadUrl());
                        }
                    }
                });
            }
            return essayPage(essayPage);
        }
        return null;
    }

    public Page<Essay> essayPage(Page<Essay> essayPage) {
        return getEssayPage(essayPage, stringRedisTemplate);
    }

    static Page<Essay> getEssayPage(Page<Essay> essayPage, StringRedisTemplate stringRedisTemplate) {
        essayPage.getRecords().forEach(v -> {
            if (v.getContext().length() > 100) {
                v.setContext(v.getContext().substring(0,100) + "...");
            }
            String viewNum = stringRedisTemplate.opsForValue().get("user:view:" + v.getId());
            String bookMark = stringRedisTemplate.opsForValue().get("user:bookMark:" + v.getId());
            String reply = stringRedisTemplate.opsForValue().get("user:reply:" + v.getId());
            String like = stringRedisTemplate.opsForValue().get("user:like:" + v.getId());
            if (viewNum == null) {
                stringRedisTemplate.opsForValue().set("user:view:" + v.getId(),String.valueOf(v.getViewNum()));
            } else {
                v.setViewNum(Integer.valueOf(viewNum));
            }
            if (bookMark == null) {
                stringRedisTemplate.opsForValue().set("user:bookMark:" + v.getId(),String.valueOf(v.getFavorNum()));
            } else {
                v.setFavorNum(Integer.valueOf(bookMark));
            }
            if (reply == null) {
                stringRedisTemplate.opsForValue().set("user:reply:" + v.getId(),String.valueOf(v.getReplayNum()));
            } else {
                v.setReplayNum(Integer.valueOf(reply));
            }
            if (like == null) {
                stringRedisTemplate.opsForValue().set("user:like:" + v.getId(),String.valueOf(v.getClickNum()));
            } else {
                v.setClickNum(Integer.valueOf(like));
            }
        });
        return essayPage;
    }
}
